# coding: utf-8
import socket
import json


def custom_html():
    sk = socket.socket()
    sk.bind(('127.0.0.1', 8008))
    sk.listen(3)
    print('sever is listening...')

    while True:
        client_connection, client_address = sk.accept()
        print('link addr:' + str(client_address))  # 打印客户端发来的嵌套字
        print('-------------------')
        data = client_connection.recv(1024)
        tempstr = data.decode('utf8')
        print(tempstr)
        print('-------------------')

        # split
        temparr = tempstr.split('\n');
        print('SSSSSSSSSSS: ' + temparr[8])
        # tempjson1 = tempstr.replace("\r", "\",\r\"");
        # tempjson2 = tempjson1.replace(":", "\":\"");
        # tempjson3 = tempjson2.replace("\n", "");
        tempjson3 = temparr[8]

        with open(r'test.json', 'r+') as f5:
            content = str(tempjson3)
            f5.seek(0)
            f5.write('{' + content + '}')

        '''
        t = "{ask:aaa}"
        with open("test.json", "w") as f:
            f.write(t)
        '''
        with open('test.json', 'rb') as f:
            html_data = f.read()

        client_connection.send(bytes('HTTP/1.1 201 OK\r\n\r\n', 'utf8'))
        client_connection.sendall(html_data)
        client_connection.close()


if __name__ == '__main__':
    custom_html()
